import http from '@/utils/http/axios'
import { RequestOptions } from '@/utils/http/axios/types'
import { AxiosRequestConfig, Method } from 'axios'
import request from '@/utils/http/axios/request'

import {
  ApiFunc,
  ApiResult,
  ApiResultStatus,
  CommandResultCallback,
  CommandSuccessCallbackOption,
  FailCallback,
  QueryResultCallback,
} from '@/api/chunfeng/apiTypes'
import { handleError } from '@/utils/error-handle'
import { message } from 'ant-design-vue'

export const apiRequest1 = (
  url: string,
  method: Method,
  params: any,
  options?: RequestOptions,
): Promise<ApiResult> => {
  return http.request(
    {
      url: url,
      method: method,
      params,
    },
    options,
  )
}

export function apiRequest<T>(url: string, method: Method, params?: any): Promise<T> {
  let requestOption: AxiosRequestConfig = { url: url, method: method, params }
  if (method.toUpperCase() === 'POST') {
    requestOption = {
      url: url,
      method: method,
      data: params,
    }
  }
  return new Promise<T>((resolve, reject) => {
    request
      .request(requestOption)
      .then((res) => {
        const apiResult = res.data
        // if (apiResult.success) {
        resolve(apiResult.data)
        // } else {
        //   reject(apiResult.status)
        // }
      })
      .catch((status: ApiResultStatus) => {
        console.log(`catch status:[${JSON.stringify(status)}]`)
        handleError(status.code, status.message)
      })
  })
}

const defaultFailCallback: FailCallback = (status) => {
  message.info({
    content: `${status.message}[${status.code}]`,
    duration: 5,
  })
}

const defaultCommandSuccessCallbackOption: CommandSuccessCallbackOption = {
  message: '操作成功',
  callback: () => {},
}

export const useHttpRequest = () => {
  function executeQueryRequest<T>(
    apiFunc: ApiFunc<T>,
    successCallback: QueryResultCallback,
    failCallback: FailCallback = defaultFailCallback,
  ) {
    apiFunc
      .then((result) => {
        successCallback(result)
      })
      .catch((status) => {
        failCallback && failCallback(status)
      })
  }

  function executeCommandRequest<T>(
    apiFunc: ApiFunc<T>,
    successCallbackOption: CommandSuccessCallbackOption,
    failCallback: FailCallback = defaultFailCallback,
  ) {
    apiFunc
      .then((_) => {
        const msg = successCallbackOption.message
        const callback = successCallbackOption.callback
        msg && message.success(msg, 3)
        callback && callback()
      })
      .catch((status) => {
        failCallback(status)
      })
  }

  return { executeQueryRequest, executeCommandRequest }
}
